<template>
    <div>
        <h3>图片列表</h3>
        <UploadImagePreviewList :image-list="imageUrls" @on-preview="showLightbox" @on-remove="handleRemove" />
        <Lightbox
            :image-list="imageUrls"
            :visible="lightboxVisible"
            :initial-index="currentPreviewIndex"
            @update:visible="handleLightboxChange"
            @close="onLightboxClose"
        />
    </div>
</template>

<script setup lang="ts">
import { ref } from "vue";

import Lightbox from "@/components/lightbox/index.vue";

const imageUrls = ref([
    "https://picsum.photos/id/17/300/400",
    "https://picsum.photos/id/127/300/400",
    "https://picsum.photos/id/13/300/400"
]);

const lightboxVisible = ref(false);
const currentPreviewIndex = ref(0);

const showLightbox = (imageSrc: string) => {
    const index = imageUrls.value.indexOf(imageSrc);
    if (index > -1) {
        currentPreviewIndex.value = index;
        lightboxVisible.value = true;
    }
};

const handleRemove = (imageSrc: string) => {
    const index = imageUrls.value.indexOf(imageSrc);
    if (index > -1) {
        imageUrls.value.splice(index, 1);
        // 如果删除的是当前预览的图片，需要调整 index
        if (index === currentPreviewIndex.value && imageUrls.value.length > 0) {
            // 如果删除的是最后一张，则索引前移
            currentPreviewIndex.value = Math.min(currentPreviewIndex.value, imageUrls.value.length - 1);
        }
    }
};

const handleLightboxChange = (val: boolean) => {
    lightboxVisible.value = val;
};

const onLightboxClose = () => {
    console.log("Lightbox closed");
    // 可以在这里执行关闭后的逻辑
};
</script>
